/*
 * Copyright 2013-2019 Xia Jun(3979434@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************************************
 *                                                                                     *
 *                        Website : http://www.farsunset.com                           *
 *                                                                                     *
 ***************************************************************************************
 */
package com.workcell.workdata.im.mvc.interceptor;

import com.workcell.workdata.im.annotation.ClientOrigin;
import com.workcell.workdata.im.component.holder.ClientOriginHolder;
import com.workcell.workdata.im.constant.Common;
import com.workcell.workdata.im.model.app.Origin;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 获取客户端信息 拦截器
 */
@Component
public class OriginInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

		Origin origin = new Origin();
		origin.setType(request.getIntHeader(Common.MVC_HEADER_APP_TYPE));
		origin.setVersion(request.getIntHeader(Common.MVC_HEADER_APP_VERSION));
		origin.setLanguage(LocaleContextHolder.getLocale().toLanguageTag());

		request.setAttribute(ClientOrigin.class.getName(),origin);

		ClientOriginHolder.set(origin);

		return true;

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) {
		ClientOriginHolder.remove();
	}
}
